package util;


import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtill {
    private static Connection con;
    private static String url;
    private static String user;
    private static String pwd;
    private DBUtill(){}
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("驱动加载成功！");
            InputStream is=DBUtill.class.getResourceAsStream("/db.properties");
            Properties prop=new Properties();
            prop.load(is);
            url=prop.getProperty("url");
            user=prop.getProperty("user");
            pwd=prop.getProperty("password");
            System.out.println(url+" "+user+" "+pwd);
            con= DriverManager.getConnection(url,user,pwd);
            System.out.println("连接成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //连接数据库
    public static Connection getCon(){
        try {
            if (con==null||con.isClosed())
                con=DriverManager.getConnection(url,user,pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     *根据传入的sql语句查询，返回结果集
     * @param sql
     * @return
     */
    public static ResultSet find(String sql){
        con=getCon();
        try {
            Statement stm=con.createStatement();//创建一个容器
            ResultSet rs=stm.executeQuery(sql);//返回结果集
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *根据传入的sql语句和参数查询，返回结果集
     * @param sql
     * @param param
     * @return
     */
    public static ResultSet find(String sql,Object ...param){
        con=getCon();
        try {
            PreparedStatement pstm=con.prepareStatement(sql);
            for(int i=0;i<param.length;i++){
                pstm.setObject(i+1,param[i]);
            }
            ResultSet rs=pstm.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     *根据传入的sql语句和参数插入一条记录
     * sql: insert into 表名 values(?,?,?...)
     *      update 表名 set 列1=？，列2=？，...
     * @param sql
     * @param param
     */
    public static void update(String sql,Object...param){
        con=getCon();
        try {
            PreparedStatement pstm=con.prepareStatement(sql);
            for (int i=0;i<param.length;i++){
                pstm.setObject(i+1,param[i]);
            }
            pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
